package com.huicoo.forestmanager.ui.patrol.forestCampTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.adapter.PatrolNeedVerifyProblemAdapter;
import com.huicoo.forestmanager.base.BaseFragment;
import com.huicoo.forestmanager.base.BaseRecyclerItemDecoration;
import com.huicoo.forestmanager.network.HttpService;
import com.huicoo.forestmanager.network.bean.patrol.AttachmentEntity;
import com.huicoo.forestmanager.network.bean.patrol.EventTypeBean;
import com.huicoo.forestmanager.network.bean.patrol.PatrolEventEntity;
import com.huicoo.forestmanager.network.bean.patrol.UploadFileBean;
import com.huicoo.forestmanager.others.WebRefreshEvent;
import com.huicoo.forestmanager.ui.media.BrowseImageActivity;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.contract.ForestCampTaskReportEventContract;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.contract.ForestCampTaskVerifyEventContract;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.presenter.ForestCampTaskReportEventPresenter;
import com.huicoo.forestmanager.util.AttachmentHelper;
import com.huicoo.forestmanager.util.DisplayUtil;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.StringUtil;
import com.huicoo.forestmanager.util.WeakHandler;
import com.huicoo.forestmanager.util.audio.PlayAudioRecordDialog;
import com.huicoo.forestmanager.util.toast.ToastUtils;
import com.huicoo.forestmanager.widget.LoadingDialog;
import com.huicoo.forestmanager.widget.ReportEventDialog;
import com.huicoo.forestmanager.widget.StopPatrolConfirmDialog;
import com.tianditu.android.maps.GeoPoint;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2019/4/7		    Administrator
 * 进行巡查任务--任务上报的片断
 */
public class TaskUploadContainerFragment extends BaseFragment implements ForestCampTaskReportEventContract.View, PatrolNeedVerifyProblemAdapter.OnAttachmentListener {
    @BindView(R.id.tv_report_desc)
    TextView tv_report_desc;
    @BindView(R.id.rv_problem)
    RecyclerView rv_problem;
    @BindView(R.id.ll_btn)
    LinearLayout ll_btn;

    private PatrolNeedVerifyProblemAdapter adapter;

    private List<EventTypeBean.EventTypeData> eventTypeList;

    private LoadingDialog loadingDialog;
    private StopPatrolConfirmDialog finishDialog;
    private ReportEventDialog reportEventDialog;
    private OnTaskUploadListener onTaskUploadListener;

    private String recordId;
    private boolean isShowBtn;

    private WeakHandler handler;

    public static TaskUploadContainerFragment getInstance() {
        return new TaskUploadContainerFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_task_upload_container;
    }

    @Override
    protected void initView() {
        presenter = new ForestCampTaskReportEventPresenter(this);
        loadingDialog = new LoadingDialog(getActivity());

        ll_btn.setVisibility(isShowBtn ? View.VISIBLE : View.GONE);

        initRecyclerView();

        //初始获取本次任务上报的事件
        getMyReportEvent();

        handler = new WeakHandler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 333) {
                    LogUtils.v("gogogo handler message = " + (String) (msg.obj));
                    playVideo((String) msg.obj);
                }
                return false;
            }
        });
    }

    private void initRecyclerView() {
        //设置布局管理器
        rv_problem.setLayoutManager(new LinearLayoutManager(getContext()));
        //创建适配器
        adapter = new PatrolNeedVerifyProblemAdapter(null);
        adapter.setOnAttachmentListener(this);
        //设置适配器
        rv_problem.setAdapter(adapter);
        rv_problem.addItemDecoration(new BaseRecyclerItemDecoration(0, 0, 0, 2));
    }

    private void requestEventType() {
        if (loadingDialog != null) {
            loadingDialog.show();
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("Token", CustomUtils.getToken());
        ((ForestCampTaskReportEventPresenter) presenter).getEventType(params);
    }

    @OnClick(R.id.btn_problem_upload)
    public void uploadProblem() {
        // 若无事件类型的数据，发起请求获取
        if (eventTypeList == null) {
            requestEventType();
        } else {
            //直接打开上报问题面板
            showReportEventDialog();
        }
    }

    @OnClick(R.id.btn_finish_task)
    public void finishTask() {
        if (finishDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            finishDialog = new StopPatrolConfirmDialog(getActivity());
            finishDialog.setOnStopPatrolListener(new StopPatrolConfirmDialog.OnStopPatrolListener() {
                @Override
                public void stopPatrol(boolean toReportRecord) {
                    if (onTaskUploadListener != null) {
                        onTaskUploadListener.finishTask(toReportRecord);
                    }
                }
            });
        }
        finishDialog.showDialog();
    }

    // 打开上报问题面板
    private void showReportEventDialog() {
        reportEventDialog = new ReportEventDialog(getActivity());
        reportEventDialog.setOnReportEventListener(new ReportEventDialog.OnReportEventListener() {
            @Override
            public void uploadFile(HashMap<String, String> params, AttachmentEntity attachmentEntity, String relateEventUID) {
                if (loadingDialog != null) {
                    loadingDialog.show();
                }
                ((ForestCampTaskReportEventPresenter) presenter).uploadFile(params, attachmentEntity);
            }

            @Override
            public void reportEvent(HashMap<String, String> params) {
                String longitude = "";
                String latitude = "";
                if (onTaskUploadListener != null) {
                    GeoPoint point = onTaskUploadListener.getCurrentGeoPoint();
                    if (point == null) {
                        ToastUtils.show("无法获取当前位置，请检查是否开启GPS位置信息");
                        return;
                    }
                    longitude = String.valueOf((double) point.getLongitudeE6() / 1E6);
                    latitude = String.valueOf((double) point.getLatitudeE6() / 1E6);
                }
                if (loadingDialog != null) {
                    loadingDialog.show();
                }
                params.put("Token", CustomUtils.getToken());
                params.put("RecordID", recordId);
                params.put("longitude", longitude);
                params.put("latitude", latitude);

                ((ForestCampTaskReportEventPresenter) presenter).reportEvent(params);
            }

            @Override
            public void reportEventOpenVideo(int type, String path) {
                openMedia(type, path);
            }
        });
        reportEventDialog.showPanel(eventTypeList);
    }

    @Override
    public void clickMediaAttachment(int type, String path, String filename) {
        //点击查看多媒体附件
        LogUtils.v("gogogo 点击多媒体附件 = " + path + "  --  " + filename);
        openMedia(type, path);
    }

    @Override
    public void clickPicAttachment(String path) {
        //点击查看图片附件
        LogUtils.v("gogogo 点击图片附件 = " + path);
        Bundle bundle = new Bundle();
        bundle.putString("imgUrl", path);
        Intent intent = new Intent(getActivity(), BrowseImageActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    // 打开媒体文件
    private void openMedia(int type, String path) {
        switch (type) {
            case PatrolNeedVerifyProblemAdapter.ATTACHMENT_VOICE:
                playVoice(path);
                break;
            case PatrolNeedVerifyProblemAdapter.ATTACHMENT_VIDEO:
                String fileName = StringUtil.getUrlParam(path, "filename");
                File file = new File(AttachmentHelper.getFilePath(fileName));
                if (file.exists()) {
                    playVideo(file.getAbsolutePath());
                } else {
                    if (loadingDialog != null) {
                        loadingDialog.show();
                    }
                    download(path, fileName);
                }
                break;
            default:
                break;
        }
    }

    // 播放录音
    private void playVoice(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        PlayAudioRecordDialog dialog = new PlayAudioRecordDialog(activity);
        dialog.showDialog(path, new PlayAudioRecordDialog.OnPlayVoiceErrorListener() {
            @Override
            public void onError() {
                ToastUtils.show("录音播放异常，请重试");
            }
        });
    }

    // 播放视频
    private void playVideo(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        Dialog dialog = new Dialog(activity, R.style.PlayVideoDialog);
        dialog.setCanceledOnTouchOutside(false);
        //创建video view
        RelativeLayout relativeLayout = new RelativeLayout(activity);
        VideoView mVideoView = new VideoView(activity);
        mVideoView.setVideoPath(path);
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                LogUtils.v("gogogo play video complete");
                dialog.dismiss();
            }
        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                LogUtils.v("gogogo play video fail");
                dialog.dismiss();
                boolean isDelete = AttachmentHelper.deleteFile(path);
                LogUtils.v("gogogo delete file = " + isDelete);
                ToastUtils.show("视频播放异常，请重试");
                return false;
            }
        });
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        relativeLayout.addView(mVideoView, layoutParams);
        //dialog添加view
        ViewGroup.LayoutParams rootLayoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog.setContentView(relativeLayout, rootLayoutParams);
        Window mWindow = dialog.getWindow();
        if (mWindow != null) {
            WindowManager.LayoutParams lp = mWindow.getAttributes();
            int mScreenWidth = DisplayUtil.getScreenWidth(activity);
            int mScreenHeight = DisplayUtil.getScreenHeight(activity);
            lp.width = mScreenWidth; // 宽度
            lp.height = (int) (mScreenHeight * 0.6); // 高度
            mWindow.setAttributes(lp);
        }
        dialog.show();
        mVideoView.start();
    }

    //获取本次任务上报的事件
    private void getMyReportEvent() {
        if (loadingDialog != null) {
            loadingDialog.show();
        }
        HashMap<String, String> params = new HashMap<>();
        params.put("Token", CustomUtils.getToken());
        params.put("RecordID", recordId);  //巡查ID
        params.put("PageIndex", "1");
        params.put("PageSize", "500");
        ((ForestCampTaskReportEventPresenter) presenter).getMyReportEvent(params);
    }

    // 与activity关联的接口回调
    public interface OnTaskUploadListener {
        void finishTask(boolean toReportRecord);

        GeoPoint getCurrentGeoPoint();
    }

    public void setOnTaskUploadListener(OnTaskUploadListener listener) {
        this.onTaskUploadListener = listener;
    }

    public void setRecordId(String recordId) {
        this.recordId = recordId;
    }

    public void setButtonShow(boolean isShow) {
        this.isShowBtn = isShow;
        if (ll_btn != null) {
            ll_btn.setVisibility(isShowBtn ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void getEventTypeSuccess(List<EventTypeBean.EventTypeData> Data) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        this.eventTypeList = Data;
        //打开上报问题面板
        showReportEventDialog();
    }

    @Override
    public void uploadFileSuccess(UploadFileBean.UploadFileData Data, int attachmentType, int during) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (reportEventDialog != null && reportEventDialog.isShowing()) {
            reportEventDialog.addFilePath(attachmentType, Data.FileName, Data.ThumbnailFile, during);
        }
    }

    @Override
    public void reportEventSuccess() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        ToastUtils.show("事件上报成功");
        if (reportEventDialog != null) {
            reportEventDialog.dismiss();
        }

        //上报事件成功，刷新本次任务上报事件列表
        getMyReportEvent();
        //通知web刷新
        EventBus.getDefault().post(new WebRefreshEvent(""));
    }

    @Override
    public void getMyReportEventSuccess(List<PatrolEventEntity> Data) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        tv_report_desc.setText(String.format("已上报%s个问题", String.valueOf(Data.size())));
        adapter.setNewData(Data);
    }

    @Override
    public void fail(String msg) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        ToastUtils.show(msg);
    }

    //视频附件下载
    private Thread downloadThread;

    private void download(String fileUrl, String fileName) {
        Call<ResponseBody> call = HttpService.getInstance().downloadFile(fileUrl);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                if (response.body() != null) {
                    LogUtils.v("gogogo download file result = " + response.message() + "  length  " + response.body().contentLength() + "  type " + response.body().contentType());
                    if (response.body().contentLength() <= 0) {
                        ToastUtils.show("附件下载失败，请检查附件地址是否正确");
                        return;
                    }
                    ToastUtils.show("正在下载附件");
                    //建立一个文件
                    File file = AttachmentHelper.createFile(fileName);
                    //下载文件放在子线程
                    downloadThread = new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            //保存到本地
                            AttachmentHelper.writeFile2Disk(response, file, new ForestCampTaskVerifyEventContract.FileDownloadCallBack() {
                                @Override
                                public void onLoading(final long current, final long total) {
                                    if (current >= total) {
                                        if (file != null) {
                                            ToastUtils.show("下载完成");
                                            if (loadingDialog != null) {
                                                loadingDialog.dismiss();
                                            }
                                            Message msg = new Message();
                                            msg.what = 333;
                                            msg.obj = file.getAbsolutePath();
                                            handler.sendMessageDelayed(msg, 300);
                                        }
                                    }
                                }
                            });

                        }
                    };
                    downloadThread.start();

                } else {
                    ToastUtils.show("请求失败，请重试");
                }
            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                //数据请求失败
                t.printStackTrace();
                ToastUtils.show("请求失败，请重试");
            }
        });
    }

    //中断下载线程
    private void stopDownloadFile() {
        if (downloadThread != null && !downloadThread.isInterrupted()) {
            downloadThread.interrupt();
        }
        downloadThread = null;
    }

    @Override
    public void onDestroy() {
        stopDownloadFile();
        super.onDestroy();
    }
}
